﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Tizer.Core;
using Tizer.Core.Enums;
using Tizer.Core.Helpers;
using Tizer.Core.Repository;
using Tizer.Utilities;
using Tizer.Web.Backoffice.Controls;
using Tizer.Web.Helper;
using System.Data.Objects;

namespace Tizer.Web.Backoffice
{
    /// <summary>
    /// Добавление нового аккаунта
    /// </summary>
    public partial class AccountEdit : AdminBasePage
    {
        /// <summary>
        /// Инициализация страницы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Init(object sender, EventArgs e)
        {
              BindCountryList();
              BindAccountType();

              var emptyItem = new ListItem { Text = StrNotChoosed, Value = "0" };
              ddlCity.Items.Add(emptyItem);
        }

        /// <summary>
        /// Загрузка страницы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.SetPageTitle();
             var id = QueryHelper.Value<int>("id", 0);
             if (id == 0)
                 Response.Redirect(UrlAdminDashboard);
             else
             {
                 using (var accountRepository = new AccountRepository())
                 {
                     Account account = accountRepository.GetById(id);
                     if (account != null)
                     {
                         txtAddress1.Text = account.Address;
                         txtAddress2.Text = account.Address2;
                         txtCompany.Text = account.Company;
                         txtDescription.Text = account.Description;
                         txtEmail.Text = account.Email;
                         txtFax.Text = account.Fax.ToString(CultureInfo.InvariantCulture);
                         txtICQ.Text = account.ICQ.ToString(CultureInfo.InvariantCulture);
                         
                         txtLogin.Text = account.Login;
                         ViewState["Login"] = account.Login;

                         txtPhone.Text = account.Phone.ToString(CultureInfo.InvariantCulture);
                         txtPhone2.Text = account.Phone2.ToString(CultureInfo.InvariantCulture);
                         txtPhoneMobile.Text = account.MobilePhone.ToString(CultureInfo.InvariantCulture);
                         txtPostalCode.Text = account.PostalCode.ToString(CultureInfo.InvariantCulture);
                         txtPublicEmail.Text = account.PublicEmail;
                         txtWebsite.Text = account.Website;

                         if (account.CountryID != null) ddlCountry.SelectedIndex = (int)account.CountryID;
                         else ddlCountry.SelectedIndex = 0; 
                         
                         if (account.CityID != null) ddlCity.SelectedIndex = (int)account.CityID;
                         else ddlCity.SelectedIndex = 0;

                         ddlAccountType.SelectedIndex = (int)account.AccountType;

                     }
                     else
                     {
                         Response.Redirect(UrlAdminDashboard);
                     }
                 }
             }
        }

        /// <summary>
        /// Изменить аккаунт
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Edit(object sender, EventArgs e)
        {
            if (Page.IsPostBack && Page.IsValid)
            {
                var id = QueryHelper.Value<int>("id", 0);
                if (id == 0)
                    Response.Redirect(UrlAdminDashboard);
                else
                {
                    using (var accountRepository = new AccountRepository())
                    {
                        Account account = accountRepository.GetById(id);
                        if (account != null)
                        {
                            if (ViewState["Login"].ToString() != txtLogin.Text && accountRepository.IsExsist(txtLogin.Text))
                            {
                                tizerMessage.SetMessage("Внимание", "Тайкой логин уже есть в системе! Выберете другой.", MessageType.Warning);
                            }
                            else
                            {
                                account.AccountType =
                                    EnumMetadataConverter.NumToEnum<AccountType>(ddlAccountType.SelectedIndex);
                                account.Address = txtAddress1.Text;
                                account.Address2 = txtAddress2.Text;

                                if (ddlCity.SelectedItem.Value != null && ddlCity.SelectedItem.Value != "0")
                                    account.CityID = Convert.ToInt32(ddlCity.SelectedItem.Value);
                                else
                                    account.CityID = null;

                                account.Company = txtCompany.Text;

                                if (ddlCountry.SelectedItem.Value != null && ddlCountry.SelectedItem.Value != "0")
                                    account.CountryID = Convert.ToInt32(ddlCountry.SelectedItem.Value);
                                else
                                    account.CountryID = null;

                                account.Description = txtDescription.Text;
                                account.Email = txtEmail.Text;
                                account.Fax = Convert.ToInt32(txtFax.Text);
                                account.ICQ = Convert.ToInt32(txtICQ.Text);
                                account.IsActive = chkActive.Checked;
                                account.IsApproved = chkActive.Checked;
                                account.MobilePhone = Convert.ToInt32(txtPhoneMobile.Text);
                                account.Phone = Convert.ToInt32(txtPhone.Text);
                                account.Phone2 = Convert.ToInt32(txtPhone2.Text);
                                account.PostalCode = Convert.ToInt32(txtPostalCode.Text);

                                account.PublicEmail = txtPublicEmail.Text;
                                account.Website = txtWebsite.Text;

                                editImageContent(accountRepository.Context, account);
                            }
                        }
                        accountRepository.SaveChanges();
                    }
                }
            }
        }

        /// <summary>
        /// Редактирование изображений
        /// </summary>
        /// <param name="context">Контекст для работы с БД</param>
        /// <param name="account">Объект аккаунта</param>
        private void editImageContent(ObjectContext context, Account account)
        {
            if (LogoUpload.ImageContent != null || MapUpload.ImageContent != null)
            {
                using (var imageTypeRepository = new ImageTypeRepository(context))
                {
                    ImageType logoImageType = imageTypeRepository.GetByCode("LOGO");
                    ImageType largeMapImageType = imageTypeRepository.GetByCode("COMPANY_MAP");

                    using (var imageRepository = new ImageRepository(context))
                    {
                        if (LogoUpload.ImageContent != null)
                        {
                            if (account.LogoImageID != null)
                            {
                                Tizer.Core.Image logoImage = imageRepository.GetById((int)account.LogoImageID);
                                if (logoImage != null)
                                {
                                    logoImage.ImageContent = LogoUpload.ImageContent;
                                }
                            }
                            else
                            {
                                Tizer.Core.Image logoImage = new Core.Image
                                {
                                    ImageContent = LogoUpload.ImageContent,
                                    ImageType = logoImageType,
                                    Date = DateTime.Now
                                };
                                if (logoImage != null)
                                {
                                    account.ImageLogo = logoImage;
                                    imageRepository.Add(logoImage);
                                }
                            }
                        }
                        if (MapUpload.ImageContent != null)
                        {
                            if (account.MapImageID != null)
                            {
                                Tizer.Core.Image mapImage = imageRepository.GetById((int)account.MapImageID);
                                if (mapImage != null)
                                {
                                    mapImage.ImageContent = MapUpload.ImageContent;
                                }
                            }
                            else
                            {
                                Tizer.Core.Image mapImage = new Core.Image
                                {
                                    ImageContent = MapUpload.ImageContent,
                                    ImageType = largeMapImageType,
                                    Date = DateTime.Now
                                };
                                if (mapImage != null)
                                {
                                    account.ImageMap = mapImage;
                                    imageRepository.Add(mapImage);
                                }
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Заполнение списка стран
        /// </summary>
        private void BindCountryList()
        {
            var emptyItem = new ListItem {Text = StrNotChoosed, Value = "0"};
            ddlCountry.Items.Add(emptyItem);

            using (var countryRepository = new CountryRepository())
            {
                var countries = countryRepository.GetAll();
                if (countries != null)
                {
                    foreach (var country in countries)
                    {
                        var item = new ListItem { Text = country.Name, Value = country.ID.ToString() };
                        ddlCountry.Items.Add(item);
                    }
                }
            }
        }


        /// <summary>
        /// Заполнение списка регионов/областей
        /// </summary>
        private void BindCityList(int countryId)
        {
            ddlCity.Items.Clear();

            var emptyItem = new ListItem { Text = StrNotChoosed, Value = "0" };
            ddlCity.Items.Add(emptyItem);


            using (var cityRepository = new CityRepository())
            {
                var cities = cityRepository.GetQuery().Where(x => x.Country.ID == countryId);
                if ( cities!= null)
                {
                    foreach (var city in cities)
                    {
                        var item = new ListItem { Text = city.Name, Value = city.ID.ToString() };
                        ddlCity.Items.Add(item);
                    }
                }
            }
        }

        /// <summary>
        /// Выбор страны пользователем
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DdlCountryIndexChange(object sender, EventArgs e)
        {
            int country = 0;
            int.TryParse(ddlCountry.SelectedItem.Value, out country);
            BindCityList(country);
        }

        /*
       /// <summary>
       /// Загрузка логотипа
       /// </summary>
       /// <param name="fileName"></param>
       /// <returns></returns>
       protected string UploadLogo(string fileName)
       {
           string message = string.Empty;
           if (fuLogo.HasFile)
           {
               try
               {
                   string filename = Path.GetFileName(fuLogo.FileName);
                   if (fuLogo.IsImage())
                   {
                       fuLogo.SaveAs(Server.MapPath(RootLogoUrl) + fileName);
                       return message;
                   }
                   else
                   {
                       return message = "Неверный форма файла";
                   }
               }
               catch (Exception)
               {
                   return message = "Ошибка загрузки логотипа.";
               }
           }
           return message = "Нет файла для загрузки логотипа.";
       }


       /// <summary>
       /// Загрузка логотипа
       /// </summary>
       /// <param name="fileName"></param>
       /// <returns></returns>
       protected string UploadMap(string fileName)
       {
           string message = string.Empty;
           if (fuMap.HasFile)
           {
               try
               {
                   string filename = Path.GetFileName(fuMap.FileName);
                   if (fuMap.IsImage())
                   {
                       fuMap.SaveAs(Server.MapPath(RootLogoUrl) + fileName);
                       return message;
                   }
                   else
                   {
                       return message = "Неверный форма файла";
                   }
               }
               catch (Exception)
               {
                   return message = "Ошибка загрузки логотипа.";
               }
           }
           return message = "Нет файла для загрузки логотипа.";
       }
         */

       /// <summary>
       /// Заполнение дропдауна с аккаунтами
       /// </summary>
       private void BindAccountType()
       {
           Dictionary<int, string> accountTypeList = EnumMetadataConverter.GetListItems(typeof(AccountType));
           foreach (var type in accountTypeList)
           {
               if (type.Key != 0)
               ddlAccountType.Items.Add(new ListItem {Value = type.Key.ToString(), Text = type.Value});
           }
       }

        /// <summary>
        /// Очитска формы
        /// </summary>
        public void Clear()
        {
            txtAddress1.Text = string.Empty;
            txtAddress2.Text = string.Empty;
            txtCompany.Text = string.Empty;
            txtDescription.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtFax.Text = string.Empty;
            txtICQ.Text = string.Empty;
            txtLogin.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtPhone2.Text = string.Empty;
            txtPhoneMobile.Text = string.Empty;
            txtPostalCode.Text = string.Empty;
            txtPublicEmail.Text = string.Empty;
            txtWebsite.Text = string.Empty;
        }
    }
}